<template>
  <view>
    <u-form :model="model" :rules="rules" labelPosition="top" ref="form" labelWidth="auto" :labelStyle="{
      fontSize: '14px',
      color: '#B2B2B2',
      lineHight: '20px'
    }">
      <view class="basic-style">
        <view class="basic-title basic-border">基本信息</view>
        <u-form-item label="单据编号" required>
          <u--input v-model="model.billNo" disabled></u--input>
        </u-form-item>
        <u-form-item label="申请人" required>
          <h-select-person-input style="width: 100%" disabled v-model="model.proposer" placeholder="请选择申请人"
            border="surround" suffixIcon="arrow-down-fill" :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.proposer"></h-select-person-input>
        </u-form-item>

        <u-form-item label="申请部门" required>
          <h-select-depart-input disabled v-model="model.proposerDeptId" :departName="model.proposerDeptText"
            placeholder="请选择部门" border="surround" style="width: 100%" suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }" :title.sync="model.proposerDeptText"
            @detail="ontenderDeptDetail"></h-select-depart-input>
        </u-form-item>
        <u-form-item label="申请时间" required>
          <u--input v-model="model.createTime" disabled></u--input>
        </u-form-item>
        <u-form-item label="借款所属团队" prop="teamId" required>
          <h-select-team-input :proposerDeptId="model.proposerDeptId"  isApi="travellingExpenses" style="width: 100%" v-model="model.teamId" objectField="model.teamId"
            placeholder="请选择借款所属团队" border="surround" suffixIcon="arrow-down-fill" :suffixIconStyle="{ color: '#B2B2B2' }" :tdlx="3" @change="resetProject" @input="teamBack"></h-select-team-input>
        </u-form-item>
        <u-form-item label="申请公司" prop="companyId" required>
          <h-select-company-input style="width: 100%" v-model="model.companyId" border="surround" placeholder="请选择公司"
            suffixIcon="arrow-down-fill" :suffixIconStyle="{ color: '#B2B2B2' }" objectField="model.companyId"
            @change="resetProject"></h-select-company-input>
        </u-form-item>
        <u-form-item label="使用日期" prop="useDate" required>
          <h-time-select mode="date" v-model="model.useDate" :minDate="(new Date()).getTime()" placeholder="请选择使用日期" border="surround"
            suffixIcon="calendar-fill" :suffixIconStyle="{ color: '#B2B2B2' }"
            @value-change="onUseDateChange"></h-time-select>
        </u-form-item>

				<u-form-item label="费用所属年度" prop="teamYear" v-if="model.teamYear=='2023'">
					<h-select-input-tag disabled style="width: 100%" dictName="tdnd_type" v-model="model.teamYear"
						placeholder="请选择费用所属年度" border="surround" suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"></h-select-input-tag>
				</u-form-item>
        <u-form-item label="是否关联项目">
          <h-radio-group v-model="model.isFree" dictName="YES_OR_NO" @change="isFreeChange"></h-radio-group>
        </u-form-item>
        <u-form-item label="关联项目" prop="projectId" :required="this.model.isFree === '1' ? true : false">
          <h-select-project-input ref="projectSelect" :queryParamType="'1'" v-model="model.projectId" @input="handleProjectSelect"
            :disabled="!model.companyId || !model.teamId || model.isFree == 0" :signUnit="model.companyId" :teamName2="model.teamId"
            style="width: 100%" placeholder="请选择项目名称" objectField="model.projectId" border="surround"
            suffixIcon="arrow-down-fill" :suffixIconStyle="{ color: '#B2B2B2' }"></h-select-project-input>
        </u-form-item>
				<u-form-item label="项目编号" prop="projectCode">
					<u--input disabled placeholder="请输入项目编号" v-model="model.projectCode"></u--input>
				</u-form-item>
				<u-form-item label="业绩归属年度" prop="projectYear">
				  <h-select-input-tag
						disabled
						class="w-100"
				    v-model="model.projectYear"
				    placeholder="请选择业绩归属年度"
				    border="surround"
				    dictName="yjgsnd"
				    suffixIcon="arrow-down-fill"
				    :suffixIconStyle="{ color: '#B2B2B2' }"
				  />
				</u-form-item>
        <u-form-item label="借款方式" prop="borrowMode" required>
					<h-dict-select
						style="width: 100%" 
						v-model="model.borrowMode" 
						placeholder="请选择借款方式" 
						dictName="borrow_money"
						border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{color: '#B2B2B2'}"
						@change="onBorrowModeChange"
					></h-dict-select>
        </u-form-item>
        <u-form-item label="借款用途" prop="purpose" required>
					<h-dict-select
						style="width: 100%" 
						v-model="model.purpose" 
						placeholder="请选择借款用途" 
						dictName="borrow_purpose"
						border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{color: '#B2B2B2'}"
					></h-dict-select>
        </u-form-item>
        <u-form-item label="归还日期" prop="returnDate" required>
          <h-time-select mode="date" v-model="model.returnDate" placeholder="请选择归还日期" border="surround"
            suffixIcon="calendar-fill" :suffixIconStyle="{ color: '#B2B2B2' }"
            @value-change="onReturnDateChange" :minDate="moment(model.createTime).valueOf()" :maxDate="moment(model.createTime).add(45, 'days').valueOf()"></h-time-select>
        </u-form-item>
        <u-form-item label="借款金额(元)" prop="amount" required>
          <u--input v-model="model.amount" :min="0" :max="99999999" placeholder="请输入借款金额"></u--input>
        </u-form-item>
        <view style="color: #909399; font-size: 14px;">
          可借款金额：
          <text>{{ money.borrowMoney }}</text>
          元，
          <text>冻结金额：{{ money.freezeAmount }}</text>
          元（冻结金额 = 未提交借款单借款金额 + 处理中借款单借款金额）
        </view>
        <u-form-item label="借款说明" prop="borrowExplain" required>
          <u--textarea :confirmType="null" count :maxlength="500" v-model="model.borrowExplain"
            placeholder="请输入借款说明"></u--textarea>
        </u-form-item>
      </view>

      <view class="basic-style" v-if="borrowFlag">
        <view class="basic-title basic-border">收款信息</view>
				<u-form-item label="领款人" prop="payee" required>
				  <h-select-person-input style="width: 100%" disabled v-model="model.payee" placeholder="请选择领款人" border="surround"
				    suffixIcon="arrow-down-fill" :suffixIconStyle="{ color: '#B2B2B2' }"
				    objectField="model.proposer"></h-select-person-input>
				</u-form-item>
        
        <u-form-item label="开户银行" prop="bankName" required>
          <u--input v-model="model.bankName" placeholder="请输入开户银行"></u--input>
        </u-form-item>
        <u-form-item label="银行账户" prop="bankAccountNo" required>
          <u--input v-model="model.bankAccountNo" placeholder="请输入银行账户"></u--input>
        </u-form-item>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border">附件信息</view>
        <view class="py-1 space-y-1" style="width: 100%">
          <view style="color: red">
            提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！
          </view>
          <h-upload-file v-model="model.attachments" :isIcon="false"></h-upload-file>
          <file-list v-if="model.attachments" v-model="model.attachments" :isDelete="true"></file-list>
        </view>
      </view>
			<view class="space-x-1 px-1 btn_position">
			  <u-button :disabled="isSubmit" type="primary" :plain="true" text="保存" @click="onDraft"></u-button>
			  <u-button :disabled="isSubmit" type="primary" text="保存并提交" @click="onSubmit"></u-button>
			</view>
			<view style="height: 100rpx"></view>
    </u-form>

    <u-modal :show="visibleModal" title="提示" :closeOnClickOverlay="true" :asyncClose="true"
      @confirm="visibleModal = false">
      <view class="slot-content">
        <view>
          {{ userInfo.userName }}！你有{{ money.num }}笔借款未结清，合计未还金额{{
            money.outstandingAmount
          }}元，以及冻结金额{{
  money.freezeAmount
}}元。根据公司财务管理要求，借款未还金额累计不能超过{{
  money.canBorrow
}}元，请及时还清借款。
        </view>
      </view>
    </u-modal>
    <u-toast ref="uToast"></u-toast>
    <ProcessNodeConfiguration ref="processConfig" @ok="onOk"></ProcessNodeConfiguration>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import moment from 'moment'
import {
  gainBillNo,
  getUserByEmpid,
  gainBorrowMoney,
  add,
  info,
  edit
} from '@/api/finance/ErpFinanceLoanBillForm'
import fileList from '@/pages/synergy/components/fileList.vue'
import ProcessNodeConfiguration from '@/components/ProcessNodeConfiguration/ProcessNodeConfiguration.vue' // 流程节点配置人员选择弹窗
import { filterMultiDictText, initDictOptions } from '@/utils/JDictSelectUtil.js'
export default {
  name: 'ErpFinanceLoanBillForm',
  components: { fileList, ProcessNodeConfiguration },
  data() {
    return {
			borrowFlag: true, // 借款方式
      visibleModal: false,
      loading: false,
      info: false,
      id: '',
			moment,
      model: {
        amount: '',
        borrowExplain: '',
				teamYear: '',
        repaymentAmount: 0,
        travelReimbursementAmount: 0,
        expenseReimbursementAmount: 0,
        settleAccounts: '0',
        checkStatus: 0,
        isFree: '1',
        billNo: '',
        teamId: null,
        borrowMode: null,
        purpose: null,
        projectId: null,
        projectType: null,
        proposer: '',
        proposerDeptId: '',
        createTime: '',
        returnDate: '',
        payee: '',
        useDate: '',
        bankName: null,
        bankAccountNo: null,
        bpmBizTitle: '',
        attachments: null,
        companyId: "",
      },
      money: {
        borrowMoney: 0,
        canBorrow: 0,
        freezeAmount: 0,
        num: 0,
        outstandingAmount: 0,
      },
      rules: {
        useDate: [
          { required: true, message: '请选择使用日期!', trigger: 'change' },
        ],
        amount: [
          { required: true,type: 'number', message: '请输入借款金额!', trigger: ['blur', 'change'] },
          {
            pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/,
            message: '请输入正确的借款金额!',
          },
        ],
        borrowMode: [
          { required: true, message: '请选择借款方式!', trigger: 'blur' },
        ],
        returnDate: [
          { required: true, message: '请选择归还日期!', trigger: 'change' },
        ],
        purpose: [
          { required: true, message: '请选择借款用途!', trigger: 'blur' },
        ],
        borrowExplain: [
          { required: true, message: '请输入借款说明!', trigger: 'blur' },
        ],
        payee: [
          { required: true, message: '请选择领款人!', trigger: 'change' },
        ],
        bankName: [
          { required: true, message: '请输入开户银行!', trigger: 'blur' },
        ],
        bankAccountNo: [
          { required: true, message: '请输入银行账户!', trigger: 'blur' }
        ],
        projectId: [
          { required: true, message: '请选择关联项目!', trigger: 'change' },
        ],
        teamId: [
          { required: true, message: '请选择借款所属团队!', trigger: 'change' },
        ],
        companyId: [
          { required: true, message: '请选择所属公司!', trigger: 'change' },
        ],
      },
			dictOptions: {},
      isSubmit: false,
      //代码生成后需手动设置流程编码
      //代码生成后需手动设置流程编码
      flowCode: 'onl_erp_finance_loan_bill',
      formUrl: "/erp/finance/borrow/modules/ErpFinanceLoanBillForm",
      formUrlMobile: "/pages/synergy/loanBill",
      processId: '1519139387793809409',
      beanName:"erpFinanceLoanBillServiceImpl"
    }
  },
  onLoad({ id }) {
    this.id = id || ''
  },
  created() {
    if (this.id) {
      this.initInfo()
    } else {
      this.initBillNo()
      this.initForm()
      this.initMoney()
      // this.initUser()
    }
		this.initDicts()
  },
  computed: {
    ...mapState(['userInfo']),
  },
  methods: {
		initDicts(){
			initDictOptions('erp_omc_team_manager,alias_name,id').then((res) => {
				if (res.success) {
					this.$set(this.dictOptions, 'teamManager', res.result)
				}
			})
		},
    // 获取单据编号
    async initBillNo() {
      const res = await gainBillNo({ proposer: this.userInfo.empId })
      this.model.billNo = res.result
      this.model.bpmBizTitle = this.userInfo?.employee?.name + '-' + this.model.billNo //标题
    },
    // 获取可借款金额等
    async initMoney(proposer = this.userInfo.empId, amount = 0) {
      const response = await gainBorrowMoney({
        proposer: proposer,
        amount: amount,
      })
      Object.assign(this.money, response.result)
    },
    // 初始化新增需要的数据
    initForm() {
      this.model.proposer = this.userInfo.empId //当前登录人
      this.model.proposerDeptId = this.userInfo.deptId //当前登录人部门
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
      this.model.payee = this.userInfo.empId //领款人
      this.$set(this.model, 'bankName', this.userInfo?.employee?.bankName) //开户行
      this.$set(this.model, 'bankAccountNo', this.userInfo?.employee?.bankCard) //银行卡号
    },
    async initInfo() {
      // this.$set(this.model, 'amount', 0)
      const response = await info({ id: this.id })
      const data = response?.result || {}
      this.model = Object.assign({}, data)
			if (data.borrowMode == 1) {
				this.borrowFlag = false
			} else {
				this.borrowFlag = true
			}
			if (data.isFree == '0') {
			  this.model.projectId = ''
			  this.rules.projectId[0].required = false
				this.$refs.form.clearValidate('projectId')
			}
			if (data.isFree == '1') {
				this.rules.projectId[0].required = true
			}
			
			let proposer = await null
			let amount = await 0
			if (this.id) {
				proposer = await data.proposer
				amount = await data.amount
			} else {
				proposer = await this.userInfo.empId
			}
			this.initMoney(proposer, amount) // 获取可借款金额
    },
		
		// 点击借款方式
		onBorrowModeChange (item){
			if (item == 1) {
				this.borrowFlag = false
			} else {
				this.borrowFlag = true
			}
		},
		teamBack(item){
			this.$set(this.model,'teamYear',item.tdnd)
		},
    resetProject(item) {
      this.model.projectId = ''
      this.$refs.projectSelect.title = ''
    },
    resetForm() {
      this.model.companyId = ''
      this.model.useDate = ''
      this.model.teamId = ''
      this.model.isFree = '1'
      this.model.projectId = ''
      this.model.borrowMode = ''
      this.model.purpose = ''
      this.model.returnDate = ''
      this.model.amount = ''
      this.model.bankName = ''
      this.model.bankAccountNo = ''
      this.model.attachments = null
    },
		handleProjectSelect (data) {
			this.$set(this.model, 'projectCode', data?.finalNo || '')
			this.$set(this.model, 'projectYear', data?.year || '')
		},
    isFreeChange(val) {
      if (val === '0') {
        this.model.projectId = ''
        this.model.projectCode = ''
        this.model.projectYear = ''
        this.rules.projectId[0].required = false
				this.$refs.form.clearValidate('projectId')
      }
      if (val === '1') {
				this.rules.projectId[0].required = true
      }
    },
    validateForm() {
      return this.$refs.form.validate().then(() => {
        if (
          this.model.amount &&
          Number(this.model.amount) > Number(this.money.borrowMoney)
        ) {
          this.visibleModal = true
          return Promise.reject('借款金额超出可借款金额')
        }
        return Promise.resolve()
      })
    },
    onUseDateChange([time]) {
      this.model.useDate = time
    },
    onReturnDateChange([time]) {
      this.model.returnDate = time
    },
		
    // 投标部门详情
    ontenderDeptDetail(item) {
      var title = ''
      if (item && item.length) {
        item.map((value, index) => {
          title = value.departName + ',' + title
        })
        title = title.substring(0, title.lastIndexOf(','))
      }
      this.model.proposerDeptText = title
    },
		
		// 获取标题
		setBpmBizTitle() {
		  // 标题 表单名称+项目名称+发起人+申请日期
		  let createTime = this.getCreateTime()
		  let teamName = filterMultiDictText(this.dictOptions['teamManager'], this.model.teamId + '')
			this.model.bpmBizTitle = (teamName ? teamName+ '-':'') + this.userInfo?.employee?.name + ' - ' + createTime + (this.model.amount? '-' + this.model.amount:'')//标题
		},
		getCreateTime() {
		  let createTime = this.model.createTime
		  let date = createTime.substring(0, 10)
		  return date.substring(0, 4) + '年' + date.substring(5, 7) + '月' + date.substring(8, 10) + '日'
		},
    async onSubmit() {
      await this.validateForm()
			this.setBpmBizTitle()
      this.isSubmit = true
      try {
        this.loading = true
        var url = ''
        if (this.id) {
          url = edit
        } else {
          url = add
        }
        const response = await url(this.model)
        uni.showToast({
          title: response.message,
          icon: 'none',
        })
        if (response.success) {
          // 获取流程列表
          if (this.model.id) {
            this.getProcessList(this.model.id)
          } else {
            // 判断添加的时候是否有返回id值
            if (response.result) {
              this.getProcessList(response.result)
            }

          }
          this.$refs.uToast.show({
            message: response.message,
            type: 'default',
            complete() {
              // that.isSubmit = false
            }
          })
        }
      } finally {
        this.loading = false
      }
    },
    async onDraft() {
      // await this.validateForm()
			this.setBpmBizTitle()
      this.isSubmit = true
      try {
        this.loading = true
        var url = ''
        if (this.id) {
          url = edit
        } else {
          url = add
        }
        const response = await url({
          ...this.model,
        })
        if (response.success) {
          this.$refs.uToast.show({
            message: response.message,
            type: 'default',
            complete() {
              this.isSubmit = false
              if (getCurrentPages().length > 1) {
                uni.navigateBack()
              } else {
                uni.reLaunch({
                  url: '/pages/home/home'
                })
              }

            }
          })
        }
      } finally {
        this.loading = false
      }
    },
    // 获取流程列表
    getProcessList(id) {
      if (this.isSubmit) {
        this.$refs.processConfig.showPopup = true
        this.$refs.processConfig.formUrl = this.formUrl
        this.$refs.processConfig.formUrlMobile = this.formUrlMobile
        this.$refs.processConfig.flowCode = this.flowCode
        this.$refs.processConfig.edit(id, this.processId, this.beanName)
      }
    },
    // 提交流程成功
    onOk() {
      this.$refs.uToast.show({
        message: '提交成功',
        type: 'success',
        complete() {
          if (getCurrentPages().length > 1) {
            uni.navigateBack()
          } else {
            uni.reLaunch({
              url: '/pages/home/home'
            })
          }

        }
      })
    }
  },
}
</script>

<style scoped lang="scss">
	@import url('@/assets/inputStyle.scss');
</style>
